#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>

#define PORT 10086

// 用于存储通信的套接字
int sock_fd;

// 用于接收服务器消息的线程函数
void* receiveMessages(void* arg) {
    char buffer[1024];
    while (1) {
        int valread = recv(sock_fd, buffer, sizeof(buffer), 0);
        if (valread > 0) {
            buffer[valread] = '\0'; // 确保字符串结束符
            printf("Server: %s\n", buffer);
        } else if (valread == 0) {
            printf("Server disconnected.\n");
            break;
        } else {
            perror("recv failed");
            break;
        }
    }
    return NULL;
}

int main() {
    struct sockaddr_in Saddr;
    char sendBuffer[1024] = {0};

    // 1. 创建套接字
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 2. 连接服务器
    Saddr.sin_family = AF_INET;
    Saddr.sin_addr.s_addr = inet_addr("192.168.61.142"); // 服务器地址
    Saddr.sin_port = htons(PORT); // 端口号，转换为网络字节序

    if (connect(sock_fd, (struct sockaddr *)&Saddr, sizeof(Saddr)) < 0) {
        perror("connect failed");
        close(sock_fd);
        exit(EXIT_FAILURE);
    }

    // 3. 创建线程用于接收消息
    pthread_t recvThread;
    pthread_create(&recvThread, NULL, receiveMessages, NULL);

    // 4. 发送消息给服务器
    while (1) {
        printf("Client: \n");
        fgets(sendBuffer, sizeof(sendBuffer), stdin); // 从终端读取客户端输入
        send(sock_fd, sendBuffer, strlen(sendBuffer), 0); // 发送消息给服务器
    }

    // 5. 关闭连接
    close(sock_fd);

    return 0;
}
